package com.module.skin

import android.app.Application
import android.text.TextUtils
import com.module.frame.ext.postEvent
import com.module.skin.ext.skinFlow
import skin.support.SkinCompatManager
import skin.support.app.SkinAppCompatViewInflater
import skin.support.app.SkinCardViewInflater
import skin.support.constraint.app.SkinConstraintViewInflater
import skin.support.design.app.SkinMaterialViewInflater
import skin.support.utils.SkinPreference

object SkinUtils {
    fun init(application: Application?, skinPath: String?, windowBg: Boolean, statusBg: Boolean) {
        SkinCompatManager.withoutActivity(application)
            .addStrategy(CustomSDCardLoader(skinPath)) //自定义SD卡皮肤
            .addInflater(SkinAppCompatViewInflater()) // 基础控件换肤初始化
            .addInflater(SkinMaterialViewInflater()) // material design 控件换肤初始化[可选]
            .addInflater(SkinConstraintViewInflater()) // ConstraintLayout 控件换肤初始化[可选]
            .addInflater(SkinCardViewInflater()) // CardView v7 控件换肤初始化[可选]
            .setSkinStatusBarColorEnable(statusBg) // 关闭状态栏换肤，默认打开[可选]
            .setSkinWindowBackgroundEnable(windowBg) // 关闭windowBackground换肤，默认打开[可选]
            .loadSkin()
    }

    fun isUse(skinName: String): Boolean {
        var use = false
        try {
            if (SkinPreference.getInstance().skinName == skinName) {
                use = true
            }
        } catch (e: Exception) {
        }
        return use
    }

    /**
     * 恢复默认
     */
    fun restore() {
        // 恢复应用默认皮肤
        SkinCompatManager.getInstance().restoreDefaultTheme()
        postEvent(skinFlow, true)
    }

    /**
     * 应用内皮肤，指定皮肤
     */
    fun setSkin(skinName: String?) {
        if (TextUtils.isEmpty(skinName)) {
            SkinUtils.restore()
            return
        }
        SkinCompatManager.getInstance()
            .loadSkin(skinName, SkinCompatManager.SKIN_LOADER_STRATEGY_BUILD_IN) // 后缀加载
        postEvent(skinFlow, true)
    }

    /**
     * SD卡内皮肤，指定皮肤
     */
    fun setSDSkin(skinName: String?) {
        if (TextUtils.isEmpty(skinName)) {
            SkinUtils.restore()
            return
        }
        SkinCompatManager.getInstance()
            .loadSkin(skinName, CustomSDCardLoader.SKIN_LOADER_STRATEGY_SDCARD)
        postEvent(skinFlow, true)
    }

    /**
     * 加载记录的皮肤包
     */
    fun setSkin() {
        SkinCompatManager.getInstance().loadSkin()
        postEvent(skinFlow, true)
    }
}